﻿/**************************************************************
 *
 * 唯一标识：73c73df0-ab07-4cb3-97d9-95c6c74accc5
 * 命名空间：Microsoft.Extensions.DependencyInjection
 * 创建时间：2023/9/3 7:35:55
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：
 *
 **************************************************************/

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Sgr.BackGroundTasks;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// 扩展
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        public const string CleanupBackgroundTaskId = "CleanupBackgroundTask";

        public static IServiceCollection AddSgrBackGroundTasksCore(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddHttpClient();

            //// Configure<TOptions> 方法会确保相关的 IOptions<TOptions>、IOptionsSnapshot<TOptions>、IOptionsMonitor<TOptions> 等服务已注册，
            //// 无需你手动再调用 AddOptions<TOptions>()。
            //services.AddOptions<BackGroundTaskOptions>();

            services.TryAddSingleton<IBackGroundExceptionHandle, DefaultBackGroundExceptionHandle>();
            services.TryAddSingleton<IBackGroundTaskExecutor, DefaultBackGroundTaskExecutor>();

            services.TryAddSingleton<IBackGroundTaskManager, NoBackGroundTaskManager>();
            services.TryAddSingleton<IRecurringTaskManager, NoRecurringTaskManager>();

            services.TryAddSingleton<HttpRequestBackGroundTask>();

            services.AddBackGroundTask<CleanupBackgroundTask>();
            services.AddBackGroundTask<HttpRequestBackGroundTask, HttpRequestArgs>();

            string cron = configuration.GetValue<string>("Sgr:BackGroundTasks:Cron:CleanupBackgroundTask") ?? "0 0 1 * * ?"; // 每天夜间1点执行一次
            services.Configure<BackGroundTaskOptions>(opts =>
            {
                opts.RegistRecurringTask<CleanupBackgroundTask>(
                    CleanupBackgroundTaskId,
                     "处理清理资源的周期性任务",
                     cron
                 );
            });

            return services;
        }
    }
}